package com.schoolinfo.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestUtil {
	private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6',
		'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * 使用sha-1算法加密密码
	 * @param password
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String encrypt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException
	{
		MessageDigest md  = MessageDigest.getInstance("sha-1");
		byte[] pbyte = password.getBytes("ISO-8859-1");
		String oldp = new String(pbyte,"ISO-8859-1");
		md.update(pbyte);
		StringBuffer sb = new StringBuffer();
		byte[] newByte = md.digest();
		String newPassword = new String(newByte,"ISO-8859-1");
		
		for (int i = 0; i < newByte.length; i++) {              
            if (Integer.toHexString(0xFF & newByte[i]).length() == 1)  
            	sb.append("0").append(Integer.toHexString(0xFF & newByte[i]));  
            else  
            	sb.append(Integer.toHexString(0xFF & newByte[i]));  
        }  
	
		return sb.toString();
		
	}
	
	//测试
	public static void main(String args[]){
		try {
			System.out.println(encrypt("sha1"));
			System.out.println(System.getProperty("sun.jun.encoding"));
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static String MD5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			return hexStringFromBytes(md.digest());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	private static String hexStringFromBytes(byte[] b) {
		String hex = "";
		int msb;
		int lsb = 0;
		int i;

		// MSB maps to idx 0
		for (i = 0; i < b.length; i++) {
			msb = ((int) b[i] & 0x000000FF) / 16;
			lsb = ((int) b[i] & 0x000000FF) % 16;
			hex = hex + hexChars[msb] + hexChars[lsb];
		}
		return (hex);
	}
}

